package com.yq.day22._01string;

import java.util.Arrays;

/**
 * 自定义类的拍接口
 * 1.Comparable<Student> 类实现接口 <>泛形 只能传入student的类型
 * 2.实现接口的方法compareTo
 * 3.定义排序的规则
 *
 * @author 3307235355@qq.com
 * @since 2022/06/22 14:52
 */
public class Demo04 {
    public static void main(String[] args) {
        Student s1 = new Student("长风", 22, 80);
        Student s2 = new Student("景天", 19, 90);
        Student s3 = new Student("李明", 19, 80);
        Student[] students = new Student[]{s1, s2, s3};
        System.out.println(Arrays.toString(students));
        Arrays.sort(students);
        System.out.println(Arrays.toString(students));
    }
}

class Student implements Comparable<Student> {
    private String name;
    private int age;
    private int score;

    public Student(String name, int age, int score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    @Override
    public int compareTo(Student o) {
        //按照年龄排序从小到大
        // return this.age-o.age;
        //    反过来o
        // return o.age - this.age;

       // 如果年龄相同按照成绩从小
        if (this.age==o.age){
            return this.score-o.score;
        }
        return this.age-o.age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}' + "\n";
    }
}